#! /bin/sh

cleanup () {
  erl -pa ../src -sname genfrag_killah -eval '
    "genfrag_killah@" ++ Host = atom_to_list (node ()),
    Other = list_to_atom ("genfrag_test1@" ++ Host),
    MoreOther = list_to_atom ("genfrag_test2@" ++ Host),

    rpc:call (Other, erlang, halt, []),
    rpc:call (MoreOther, erlang, halt, [])
  ' -noshell -noinput -s erlang halt 
  wait
}

rm -rf Mnesia*

{
erl -pa ../src -sname genfrag_test1 -s mnesia -eval '
  mnesia:change_table_copy_type (schema, node (), disc_copies),
  timer:sleep (30000)'  \
  -noshell -noinput -s erlang halt &

erl -pa ../src -sname genfrag_test2 -eval '
  timer:sleep (30000)'  \
  -noshell -noinput -s erlang halt &

sleep 1

erl -pa ../src -sname genfrag_test3 -s mnesia -eval '
  "genfrag_test3@" ++ Host = atom_to_list (node ()),
  Self = node (),
  Other = list_to_atom ("genfrag_test1@" ++ Host),
  MoreOther = list_to_atom ("genfrag_test2@" ++ Host),
  pong = net_adm:ping (Other),
  pong = net_adm:ping (MoreOther),
  mnesia:change_config (extra_db_nodes, [ Other ]),
  mnesia:change_table_copy_type (schema, node (), disc_copies),
  timer:sleep (1000),

  [ Other, MoreOther ] = lists:sort (erlang:nodes ()),
  [ Other, Self ] = lists:sort (mnesia:system_info (running_db_nodes)),

  { ok, Pid } = gen_fragment:start_link (testdb, false, [ flass, 3, 2 ], []),

  [ Other, Self ] = lists:sort (mnesia:table_info (flass, ram_copies)),
  [ Other, Self ] = lists:sort (mnesia:table_info (flass_frag2, ram_copies)),
  [ Other, Self ] = lists:sort (mnesia:table_info (flass_frag3, ram_copies)),

  rpc:call (MoreOther, mnesia, start, []),
  rpc:call (MoreOther,
            mnesia,
            change_config,
            [ extra_db_nodes, [ Self, Other ] ]),
  rpc:call (MoreOther,
            mnesia,
            change_table_copy_type,
            [ schema, MoreOther, disc_copies ]),

  timer:sleep (1000),

  [ Other, MoreOther ] = lists:sort (erlang:nodes ()),
  [ Other, MoreOther, Self ] = 
    lists:sort (mnesia:system_info (running_db_nodes)),

  rpc:call (MoreOther,
            gen_fragment,
            start,
            [ testdb, false, [ flass, 3, 2 ], [] ]),

  timer:sleep (1000),

  [ [ Other, MoreOther ], [ Other, Self ], [ MoreOther, Self ] ] =
    lists:sort ([
      lists:sort (mnesia:table_info (flass, ram_copies)),
      lists:sort (mnesia:table_info (flass_frag2, ram_copies)),
      lists:sort (mnesia:table_info (flass_frag3, ram_copies))
      ])
' -noshell -noinput -s erlang halt || { cleanup; exit 1; }
} > genfrag-newnode.output 2>&1

cleanup

rm -rf Mnesia*

exit 0
